﻿using System;
using System.Collections;

namespace RH
{
   public class FormulaFieldCollection : CollectionBase, IEnumerable
   {

      public int Add(FormulaField item)
      {
         return List.Add(item);
      }

      public void Insert(int index, FormulaField item)
      {
         List.Insert(index, item);
      }
      public void Remove(FormulaField item)
      {
         List.Remove(item);
      }
      public bool Contains(FormulaField item)
      {
         return List.Contains(item);
      }
      public int IndexOf(FormulaField item)
      {
         return List.IndexOf(item);
      }
      public void CopyTo(Array array, int index)
      {
         List.CopyTo(array, index);
      }

      public bool Exists(string key)
      {
         foreach (object obj in List)
         {
            FormulaField objItm = (FormulaField)obj;
            if (objItm.Key == key)
               return true;
         }

         return false;
      }

      public FormulaField this[int index]
      {
         get { return (FormulaField)List[index]; }
         set { List[index] = value; }
      }

      private FormulaField GetByKey(string key)
      {
         foreach (object obj in List)
         {
            FormulaField objItm = (FormulaField)obj;
            if (objItm.Key == key)
               return objItm;
         }

         return null;
      }

      public FormulaField this[string key]
      {
         set
         {
            FormulaField obj = GetByKey(key);
            if (obj != null)
               obj = value;
         }
         get { return GetByKey(key); }

      }

      public new IEnumerator GetEnumerator()
      {
         return new ItemIterator(this);
      }

      private class ItemIterator : IEnumerator
      {

         private FormulaFieldCollection _itemCollection;
         private int _index = -1;

         public ItemIterator(FormulaFieldCollection ic)
         {
            _itemCollection = ic;
         }

         public bool MoveNext()
         {
            _index++;
            if (_index < _itemCollection.Count)
            {
               return true;
            }
            else
            {
               _index = -1;
               return false;
            }
         }

         public object Current
         {
            get
            {
               if (_index <= -1)
               {
                  throw new InvalidOperationException();
               }
               return _itemCollection[_index];
            }
         }

         public void Reset()
         {
            _index = -1;
         }
      }

   }
}